package com.kaiyidiannao.activity.messageInfo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.kaiyidiannao.adapter.CommonViewpagerAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.MessageBean;
import com.kaiyidiannao.model.req.model.GetMessageInfoShow;
import com.kaiyidiannao.model.req.model.PostAddFavorites;
import com.kaiyidiannao.view.ActionBarView;
import com.taplinker.core.util.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by wzg on 14-4-14.
 */
public class MessageInfoDetail extends BaseActionBarActivity implements Observer {
    private ActionBarView infoActionBar;
    private TextView message_detailTitle;
    private TextView tel;
    private ImageView message_call;
    private ImageView collect; //收藏
    private TextView message_date;
    private TextView message_name;
    private TextView message_detail;
    private MessageBean messageBean ;
    private String typeid = "56";
    private String userid ;
    private String action = "add";
    private String itemid = "";
    private String catid = "56";
    private boolean collectFlag;
    //    private SQLiteDatabase db;
    private int tip = 0;

    //    private DBHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.messageinfo_detail);
        findActionBar();
//        if(!HttpUtils.isConnected()){
//            Toast.makeText(MessageInfoDetail.this,"网络异常,请稍后重试",Toast.LENGTH_SHORT).show();
//            return;
//        }
        DataCenter.getInstance().addObserver(this);
        Intent intent = getIntent();
        itemid = intent.getStringExtra("itemid");
        Log.d("itemid ",itemid + "----------");
        //init();
        requestData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d(DataCenter.LOG_INFO, MessageInfoDetail.class.getSimpleName() + ".onDestroy");
        DataCenter.playBeanList.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);

    }

    public void findActionBar() {
        infoActionBar = (ActionBarView) findViewById(R.id.infoActionBar);
        infoActionBar.title.setText("信息矿详情");
    }

    public void init() {

        tel = (TextView) findViewById(R.id.tel);
        message_call = (ImageView) findViewById(R.id.message_call);
        message_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + tel.getText()));
                startActivity(intent);
            }
        });
        collect = (ImageView) findViewById(R.id.message_shouCang);
        if (messageBean.getIs_fav()) { // 已经收藏
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucanged));
            collectFlag = true;
        } else {
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
            collectFlag = false;
        }
        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!HttpUtils.isConnected()) {
                    showToast("离线模式，无法操作，请连接网络");
                    return;
                }

                if (messageBean == null) {
                    showToast("详情加载失败");
                    return;
                }
                if (!isLogin()) {
                    startLoginOrRegistered();
                    return;
                }

                String action = "add";
                if (collectFlag) {
                    action = "delete";
                }
                showProgressDialog();
                new PostAddFavorites(DataCenter.CATID_MESSAGE_INF, userid, action, messageBean.getItemid(), messageBean.getTitle()).execute();
            }
        });
//        message_shouCang.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                if (!isLogin()) {
//                    startLoginOrRegistered();
//                    return;
//                }
//
//                if (!messageBean.getIs_fav()) {
//                    // 收藏，点赞的catid是固定的，信息框（56）
//                    showProgressDialog();
//                    new PostAddFavorites(DataCenter.CATID_MESSAGE_INF, userid, action, messageBean.getItemid(), messageBean.getTitle()).execute();
//                    message_shouCang.setEnabled(false);
//                }
//                if(messageBean.getIs_fav()){
//                    new PostDeleteMessageInfo(userid,"delete",messageBean.getItemid(),DataCenter.CATID_MESSAGE_INF + "",1).execute();
//                    message_shouCang.setEnabled(false);
//                    showProgressDialog();
//                }
//            }
//        });
        message_detailTitle = (TextView) findViewById(R.id.message_detailTitle);
        message_date = (TextView) findViewById(R.id.message_date);
        message_name = (TextView) findViewById(R.id.message_name);
        message_detail = (TextView) findViewById(R.id.message_detail);
        //八张详情图片
        detailViewPager = (ViewPager) findViewById(R.id.detail_ViewPager);
//        db = dbHelper.getWritableDatabase();


        message_detailTitle.setText(messageBean.getTitle());
        tel.setText(messageBean.getTelephone());
        message_date.setText(messageBean.getAddtime());
        message_name.setText(messageBean.getUsername());
        message_detail.setText(messageBean.getIntroduce());
        //八张详情图片
        imageUrlList = messageBean.getPicture2();
        initViewPage();
    }


    /**
     * 请求数据
     */
    public void requestData() {
        if(DataCenter.userLogin.size()!=0){
            userid = DataCenter.userLogin.get(0).getUserid();
        }

//        showProgressDialog();
        if (!"".equals(userid)&&null!=userid) {
            new GetMessageInfoShow(Integer.parseInt(itemid), userid,catid).execute();
        } else {
            new GetMessageInfoShow(Integer.parseInt(itemid)).execute();
        }
    }


    @Override
    public void update(Observable observable, Object data) {

        closeProgressDialog();

        DataCenter.flag flag = (DataCenter.flag) data;
        Log.d("MessageInfoDetail", DataCenter.resultes);

        if (flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS) {//收藏成功,关注成功\
            if (DataCenter.successFlag.equals(DataCenter.successFlag)) {
                if (collectFlag) {//从当前的关注状态变成没有关注
                    collectFlag = false;
                    showToast(R.string.collect_cancle);
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
                } else {
                    showToast(R.string.collect_add);
                    collectFlag = true;
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucanged));
                }
            } else {
                showToast(DataCenter.msg, "收藏出现错误");
            }
        }

//        if(flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS){ //添加收藏成功
//            message_shouCang.setEnabled(true);
//            if (DataCenter.code.equals(DataCenter.successFlag)) {
//                Log.d("MessageInfoDetail", "成功");
//                message_shouCang.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.xingxing));
//                showToast(getString(R.string.collect_add));
//                requestData();
//            }
//        }
//
//        if(flag == DataCenter.flag.POST_DELETE_MESSAGE_SUCCESS){//删除收藏成功
//            message_shouCang.setEnabled(true);
//            if(DataCenter.code.equals(DataCenter.successFlag)){
//                message_shouCang.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.favoritesed));
//                Log.d("MessageInfoDetail", "成功");
//                showToast(getString(R.string.collect_cancle));
//                requestData();
//            }
//        }

        if (flag == DataCenter.flag.GET_MESSAGEINFO_SHOW_SUCCESS) {

            findViewById(R.id.scrollview_wrapping).setVisibility(View.VISIBLE);
            findViewById(R.id.realod_layout).setVisibility(View.GONE);
            messageBean = DataCenter.messageInfoShowList.get(0);
            init();
        } else if (flag == DataCenter.flag.GET_MESSAGEINFO_SHOW_FAILED) { //请求失败，重新加该页面
            showReloadView();
        }

    }

    /**
     * 初始化8张详情图片
     */
    private ViewPager detailViewPager;
    private CommonViewpagerAdapter commonViewpagerAdapter;
    private List<View> imageList = new ArrayList<View>();
    private List<String> imageUrlList = new ArrayList<String>();

    private void initViewPage() {
        commonViewpagerAdapter = new CommonViewpagerAdapter(MessageInfoDetail.this, imageList, detailViewPager, imageUrlList);

        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            View view = getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            final ImageView viewpagerItemIv = (ImageView) view.findViewById(R.id.viewpagerItemIv);
            viewpagerItemIv.setImageResource(android.R.color.white);
            imageLoader.displayImage(imageUrlList.get(i), viewpagerItemIv,super.options, null);
            viewpagerItemIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    Intent intent = new Intent();
//                    intent.setClass(SecondHandCarDetail.this, DisplayActivity.class);
//                    intent.putExtra("url", imageUrlList.get(position));
//                    startActivity(intent);
                    MessageInfoDetail.super.startImagePagerActivity(position, messageBean.getPicture());
                }
            });
            imageList.add(view);
        }
        detailViewPager.setAdapter(commonViewpagerAdapter);

        if(messageBean != null){
            if(messageBean.getPicture().length == 0){
                detailViewPager.setBackgroundResource(R.drawable.ic_default);
            }
        }
    }

    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        findViewById(R.id.scrollview_wrapping).setVisibility(View.GONE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findViewById(R.id.scrollview_wrapping).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                requestData();
            }
        });
    }

}
